import { ref, reactive } from 'vue'
import webRTCUtil from '@/webSocket/webRTCUtil/index.js'

class CallManager {
  constructor() {
    // 通话状态
    this.callState = reactive({
      isInCall: false,
      isIncoming: false,
      callType: 'video', // 'video' | 'audio'
      sessionId: null,
      callerInfo: null,
      targetUserId: null,
      callStartTime: null
    })

    // 事件回调
    this.callbacks = {
      onIncomingCall: null,
      onCallAccepted: null,
      onCallRejected: null,
      onCallEnded: null,
      onCallError: null
    }

    // 绑定 WebRTC 事件
    this.bindWebRTCEvents()
  }

  /**
   * 绑定 WebRTC 事件
   */
  bindWebRTCEvents() {
    // 扩展现有的 WebRTC 处理器
    const originalHandlers = window.webRTCHandlers || {}

    window.webRTCHandlers = {
      ...originalHandlers,

      // 收到来电邀请
      callInvite: this.handleIncomingCall.bind(this),

      // 对方接受通话
      callAccepted: this.handleCallAccepted.bind(this),

      // 对方拒绝通话
      callRejected: this.handleCallRejected.bind(this),

      // 通话结束
      callEnded: this.handleCallEnded.bind(this)
    }
  }

  /**
   * 发起通话
   * @param {Object} options - 通话选项
   */
  async startCall(options) {
    const { targetUserId, sessionId, callType = 'video', callerInfo } = options

    try {
      this.callState.isInCall = true
      this.callState.isIncoming = false
      this.callState.callType = callType
      this.callState.sessionId = sessionId
      this.callState.targetUserId = targetUserId
      this.callState.callerInfo = callerInfo
      this.callState.callStartTime = Date.now()

      // 发送通话邀请信令
      this.sendCallInvite({
        target: targetUserId,
        sessionId: sessionId,
        callType: callType,
        callerInfo: {
          name: '我', // 这里应该是当前用户的信息
          avatar: '',
          userId: 'currentUserId' // 当前用户ID
        }
      })

      console.log('发起通话:', options)
      return true
    } catch (error) {
      console.error('发起通话失败:', error)
      this.resetCallState()
      this.callbacks.onCallError?.(error)
      return false
    }
  }

  /**
   * 接听通话
   * @param {Object} callData - 通话数据
   */
  async acceptCall(callData) {
    try {
      this.callState.isInCall = true
      this.callState.callStartTime = Date.now()

      // 发送接受通话信令
      this.sendCallResponse({
        target: callData.callerInfo.userId,
        sessionId: callData.sessionId,
        accepted: true
      })

      // 开始 WebRTC 连接
      await webRTCUtil.joinRoom(callData.sessionId, callData.callerInfo.userId)

      this.callbacks.onCallAccepted?.(callData)
      console.log('接听通话:', callData)
      return true
    } catch (error) {
      console.error('接听通话失败:', error)
      this.callbacks.onCallError?.(error)
      return false
    }
  }

  /**
   * 拒绝通话
   * @param {Object} callData - 通话数据
   */
  rejectCall(callData) {
    try {
      // 发送拒绝通话信令
      this.sendCallResponse({
        target: callData.callerInfo.userId,
        sessionId: callData.sessionId,
        accepted: false
      })

      this.resetCallState()
      this.callbacks.onCallRejected?.(callData)
      console.log('拒绝通话:', callData)
      return true
    } catch (error) {
      console.error('拒绝通话失败:', error)
      return false
    }
  }

  /**
   * 结束通话
   */
  endCall() {
    try {
      console.log('CallManager: 结束通话')

      // 防止重复调用
      if (!this.callState.isInCall) {
        console.log('CallManager: 通话已经结束，忽略重复调用')
        return true
      }

      // 发送结束通话信令
      if (this.callState.sessionId && this.callState.targetUserId) {
        this.sendCallEnd({
          target: this.callState.targetUserId,
          sessionId: this.callState.sessionId
        })
      }

      // 结束 WebRTC 连接
      webRTCUtil.endCall()

      const callData = { ...this.callState }
      this.resetCallState()

      // 触发回调
      this.callbacks.onCallEnded?.(callData)
      console.log('CallManager: 通话结束完成')
      return true
    } catch (error) {
      console.error('结束通话失败:', error)
      return false
    }
  }

  /**
   * 处理来电
   */
  handleIncomingCall(data) {
    console.log('收到来电:', data)

    this.callState.isIncoming = true
    this.callState.callType = data.callType || 'video'
    this.callState.sessionId = data.sessionId
    this.callState.callerInfo = data.callerInfo
    this.callState.targetUserId = data.callerInfo.userId

    this.callbacks.onIncomingCall?.(data)
  }

  /**
   * 处理通话被接受
   */
  handleCallAccepted(data) {
    console.log('通话被接受:', data)
    this.callbacks.onCallAccepted?.(data)
  }

  /**
   * 处理通话被拒绝
   */
  handleCallRejected(data) {
    console.log('通话被拒绝:', data)
    this.resetCallState()
    this.callbacks.onCallRejected?.(data)
  }

  /**
   * 处理通话结束
   */
  handleCallEnded(data) {
    console.log('通话结束:', data)
    const callData = { ...this.callState }
    this.resetCallState()
    this.callbacks.onCallEnded?.(callData)
  }

  /**
   * 发送通话邀请信令
   */
  sendCallInvite(data) {
    const message = {
      type: 'rtc',
      method: 'join',
      data: data
    }
    this.sendSignaling(message)
  }

  /**
   * 发送通话响应信令
   */
  sendCallResponse(data) {
    const message = {
      type: 'rtc',
      method: 'callResponse',
      data: data
    }
    this.sendSignaling(message)
  }

  /**
   * 发送通话结束信令
   */
  sendCallEnd(data) {
    const message = {
      type: 'rtc',
      method: 'callEnd',
      data: data
    }
    this.sendSignaling(message)
  }

  /**
   * 发送信令消息
   */
  sendSignaling(message) {
    // 使用 webRTCUtil 的发送方法
    if (webRTCUtil && webRTCUtil.sendSignaling) {
      console.log('消息体：', message.data
      )
      webRTCUtil.sendSignaling(message.method, message.data)
    } else {
      console.warn('WebRTC 工具不可用，无法发送信令:', message)
    }
  }

  /**
   * 重置通话状态
   */
  resetCallState() {
    this.callState.isInCall = false
    this.callState.isIncoming = false
    this.callState.callType = 'video'
    this.callState.sessionId = null
    this.callState.callerInfo = null
    this.callState.targetUserId = null
    this.callState.callStartTime = null
  }

  /**
   * 设置事件回调
   */
  setCallbacks(callbacks) {
    this.callbacks = { ...this.callbacks, ...callbacks }
  }

  /**
   * 获取通话状态
   */
  getCallState() {
    return this.callState
  }

  /**
   * 获取通话时长（秒）
   */
  getCallDuration() {
    if (this.callState.callStartTime) {
      return Math.floor((Date.now() - this.callState.callStartTime) / 1000)
    }
    return 0
  }
}

// 创建单例
const callManager = new CallManager()

export default callManager
